<?php

namespace App\Models;

use App\Enums\GoodsBusinessEnum;
use App\Exceptions\ApiException;
use App\Util\ArrayUtil;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class GoodsRentMeal extends baseModel
{
    const KEY = 'meal_id';
    const TABLE = 'sp_goods_rent_meal';

    protected $table = self::TABLE;
    protected $primaryKey = self::KEY;
    protected $connection = 'mysql';

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $guarded = [];

    protected $casts = [
        'create_time' => 'datetime:Y-m-d H:i:s',
        'update_time' => 'datetime:Y-m-d H:i:s',
    ];

    public function goods_rent_sku()
    {
        return $this->hasMany(GoodsRentSku::class,'meal_id','meal_id');
    }


    /**
     * 验证套餐值是否合法
     * @param array $mealList
     */
    public static function checkMealData(array $mealList,$business_type)
    {
     $mealNames = ArrayUtil::getArrayColumn($mealList, 'meal_name');
        if (count($mealList) != count(array_unique($mealNames))) {
            throw new ApiException('很抱歉，不能存在重复的套餐组');
        }
        foreach ($mealList as $item) {
            $values = ArrayUtil::getArrayColumn($item['valueList'], 'meal_value');


            if (count($item['valueList']) != count(array_unique($values))) {
                throw new ApiException('很抱歉，不能存在重复的套餐值');
            }
            if ($business_type == GoodsBusinessEnum::RENT()->getKey()) {
                foreach ($item['valueList'] as $value) {
                    if ($value['meal_value'] > 365) {
                        throw new ApiException('很抱歉，套餐值不能大于365天');
                    }
                    if ($value['meal_value'] < 60) {
                        throw new ApiException('很抱歉，套餐值不能小于60天');
                    }
                }
            }
            if ($business_type == GoodsBusinessEnum::LEASE()->getKey()) {
                foreach ($item['valueList'] as $value) {
                    if ($value['meal_value'] > 12) {
                        throw new ApiException('很抱歉，套餐值不能大于12期');
                    }
                }
            }
        }
    }

    /**
     * 根据套餐值计算能生成的SKU总量
     * @param array $mealList
     * @return int
     */
    public static function calcSkuListTotal(array $mealList): int
    {
        $total = 1;
        foreach ($mealList as $item) {
            $total *= \count($item['valueList']);
        }
        return $total;
    }

    /**
     * 套餐组写入数据库并生成id
     * 此时的$mealList是用户端传来的
     * @param array $mealList
     */
    public static function getNewMealList(array $mealList)
    {
        // 套餐组名称合集
        $names = ArrayUtil::getArrayColumn($mealList, 'meal_name');
        // 获取到已存在的套餐组
        $alreadyData = static::getListByNames($names);
        // 遍历整理新的套餐集
        foreach ($mealList as $key => &$item) {
            $alreadyItem = ArrayUtil::getArrayItemByColumn($alreadyData, 'meal_name', $item['meal_name']);
            if (!empty($alreadyItem)) {
                // 套餐名已存在的记录meal_id
                $item['meal_id'] = $alreadyItem['meal_id'];
            } else {
                // 套餐名不存在的新增记录
                $result = static::add($item);
                $item['meal_id'] = $result['meal_id'];
            }
            // 套餐值写入数据库并生成id
            $item['valueList'] = GoodsRentMealValue::getNewValueList((int)$item['meal_id'], $item['valueList']);
        }
        return $mealList;
    }

    /**
     * 根据套餐组名称集获取列表
     * @param array $names
     *
     */
    private static function getListByNames(array $names)
    {
        $res=(new static)->whereIn('meal_name', $names)
        ->select('meal_id', 'meal_name')->get();
        return  obToArray($res);
    }

    /**
     * 新增套餐组记录
     * @param array $item
     */
    private static function add(array $item)
    {
        return self::create([
            'meal_name' => $item['meal_name'],
        ]);
    }
}
